<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
  import { query } from '@/api_bast/mssage.js'
  import {logout} from '@/api_bast/user.js'
export default {
  name: 'App',
  data(){
      return {
        path:"ws://172.16.100.22:8787/websocket/",
        socket:"",
      }
  },
  methods:{
    init () {
      console.log(this.json_object(this.resData()),'>>> 用户信息 <<<');
      if(typeof(WebSocket) === "undefined"){alert("您的浏览器不支持socket");return false;}
        // 实例化socket
        this.socket = new WebSocket(this.path+this.json_object(this.resData()).id+'?jsessionid='+localStorage.JSESSIONID);
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
    },
    open () {
      console.log("socket连接成功")
    },
    error () {
      console.log("连接错误")
    },
    getMessage (msg) {
      console.log(msg.data);
      this.$store.state.user.sai.userId = this.json_object(this.resData()).id;
      query(this.$store.state.user.sai).then(response => {
        this.loading = false;
        if(!response.resData){return false;}
        this.$store.state.user.totals = response.resData.total;
        this.$store.state.user.messagebox = response.resData.list;
      })
      let dur = msg.data=='连接成功'?'1000':'6000';
      this.$notify.info({
        onClick:this.hiden,
        title: '消息',
        duration:dur,
        message:msg.data=='连接成功'?msg.data:this.json_object(msg.data).message
      });
    },
    hiden(){
      this.$router.push({path:'/msg'});
      this.$notify.close();
    },
    send () {
      this.socket.send(params)
    },
    close () {
      console.log("socket已经关闭")
    },
    guanbi(){
      // 销毁监听
      // logout().then(response => {});
      this.socket.onclose = this.close;
    },
  },
  mounted () {
      if(localStorage.resData){this.$router.push({path:'/home'})}
  },
  watch:{
    $route(to,from){
      console.log(to.path);
      if(to.path!=='/'){
            if(this.$store.state.user.num==1){return false};
            window.setTimeout(()=>{
              this.init();// 初始化
            },500);
            this.$store.state.user.num=1;
      }
    }
  },
	created(){
    if(!localStorage.resData){this.$router.push({path:'/'});return false;}
    if(localStorage.resData==undefined){this.$router.push({path:'/'});return false;}
    // console.log(this.json_object(localStorage.resData),'>>>登录用户信息<<<');
	},
  destroyed () {
    this.guanbi();
  },
  beforeDestroy() {
    this.guanbi();
  },

}
</script>
